package network;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;

import lib.Core;
import lib.XmlPullParser;
import ru.qiwi.security.MD5;
import ru.qiwi.security.Security;
import Core.Contants;
import Core.GlobalData;
import DTO.Group;
import DTO.Provider;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.simpay.cashierandroidapp.DialogScreen;
import com.simpay.cashierandroidapp.DownloadImageTask;
import com.simpay.login.MainActivity;

public class LoadViewTask extends AsyncTask<Void, String, Object[]> {
	String logoURL = "http://update1.qiwi.com/";

	private String stringURL;
	private Packet packet;
	int idpacket;
	Context context;
	Object data;

	private ProgressDialog progressDialog;

	public LoadViewTask(int idpacket, Context contxt) {
		this.stringURL = GlobalData.url;
		this.idpacket = idpacket;
		this.packet = new Packet(idpacket, contxt, this);
		this.context = contxt;

		execute();
	} 

	public LoadViewTask(int idpacket, Context contxt, Object data) {
		this.data = data;
		this.stringURL = GlobalData.url;
		this.idpacket = idpacket;
		this.packet = new Packet(idpacket, contxt, data, this);
		this.context = contxt;

		execute();
	}

	// Before running code in separate thread
	@Override
	protected void onPreExecute() {
		progressDialog = new ProgressDialog(Core.context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

		if (idpacket == Packet.TYPE_GETGROUPS) {
			progressDialog.setMessage("Đang tải danh sách nhóm...");
		} else if (idpacket == Packet.TYPE_GETPROVIDERS) {
			progressDialog.setMessage("Đang tải danh sách nhà cung cấp...");
		} else if (idpacket == Packet.TYPE_GETRESULTCODES) {
			progressDialog.setMessage("Đang tải danh sách mã lỗi...");
		} else if (idpacket == Packet.TYPE_HEADNUMBER) {
			progressDialog.setMessage("Đang tải danh sách đầu số...");
		} else if (idpacket == Packet.TYPE_PRICETYPES) {
			progressDialog.setMessage("Đang tải danh sách mệnh giá...");
		} else if (idpacket == Packet.TYPE_GETRESULTCODES) {
			progressDialog.setMessage("Đang tải danh sách mã lỗi...");
		} else if (idpacket == Packet.TYPE_LOADLOGO) {
			progressDialog.setMessage("Đang tải logo...");
		} else {
			progressDialog.setMessage("Dữ liệu đang xử lý...");
		}

		progressDialog.setCancelable(false);
		progressDialog.setIndeterminate(false);
		progressDialog.show();

	}

	@SuppressLint("UseValueOf")
	@SuppressWarnings("unchecked")
	@Override
	protected Object[] doInBackground(Void... params) {
		synchronized (this) {
			HttpURLConnection hc = null;
			InputStream in = null;
			OutputStream out = null;
			try {
				System.out.println("__________Connect Server___________");
				if (idpacket == Packet.TYPE_HEADNUMBER) {
					URL url = new URL(
							"http://qcm.simpay.com.vn/download/headnumber.xml");
					hc = (HttpURLConnection) url.openConnection();
					in = hc.getInputStream();
					Object[] data = { new Integer(0), in };
					return data;
				} else if (idpacket == Packet.TYPE_PRICETYPES) {
					URL url = new URL(
							"http://qcm.simpay.com.vn/download/price.xml");
					hc = (HttpURLConnection) url.openConnection();
					in = hc.getInputStream();
					Object[] data = { new Integer(0), in };
					return data;
				} else if (idpacket == Packet.TYPE_LOADLOGO) {
					try {
						Vector<Group> groups = (Vector<Group>) Core
								.readData(Contants.GROUPS);
						for (Enumeration<Group> e = groups.elements(); e
								.hasMoreElements();) {
							Group g = (Group) e.nextElement();

							new DownloadImageTask("" + g.getId())
									.execute(logoURL + g.getLogo());
						}

						Vector<Provider> providers = (Vector<Provider>) Core
								.readData(Contants.PROVIDERS);
						for (Enumeration<Provider> e = providers.elements(); e
								.hasMoreElements();) {
							Provider g = (Provider) e.nextElement();

							if (e.hasMoreElements())
								new DownloadImageTask("" + g.getPrv_id())
										.execute(logoURL + g.getLogo());

							else
								new DownloadImageTask("" + g.getPrv_id(), this)
										.execute(logoURL + g.getLogo());

						}
					} catch (Exception ex) {
					}

					Object[] data = { new Integer(0), null };
					return data;
				}
				// TEST MA THE
				// else if (idpacket == Packet.TYPE_PURCHASEONLINE) {
				// sleep(3000);
				// System.out.println("_____________________");
				// String message = packet.toXML();
				// System.out.println("request" + message);
				//
				// in = new ByteArrayInputStream(getTestPurchaseOnline()
				// .getBytes());
				// XmlPullParser xml = new XmlPullParser(new
				// InputStreamReader(in,
				// "UTF-8"));
				// packet.parseXML(xml);
				// }
				else {

					String message = packet.toXML();
					System.out.println("request" + message);

					URL url = new URL(stringURL);
					hc = (HttpURLConnection) url.openConnection();
					hc.setDoInput(true);
					hc.setDoOutput(true);
					hc.setUseCaches(false);
					hc.setRequestProperty("Content-Type", "text/xml");
					hc.setRequestProperty("Content-Length",
							String.valueOf(message.length()));

					if (idpacket == Packet.TYPE_SETPUBLICKEY) {
						hc.setRequestProperty("X-Digital-Sign",
								MD5.hashAsHex(GlobalData.auth.getSign()));//
						hc.setRequestProperty("X-Digital-Sign-Alg",
								GlobalData.auth.getSignAlg());
						hc.setRequestProperty("X-Digital-Sign-Login",
								GlobalData.auth.getLogin());
					} else {
						String userCredentials = Security.getIns().getSign(
								message.getBytes("UTF-8"));
						hc.setRequestProperty("X-Digital-Sign", userCredentials);
						hc.setRequestProperty("X-Digital-Sign-Alg",
								"MD5withRSA");
						hc.setRequestProperty("X-Digital-Sign-Login",
								GlobalData.auth.getLogin());
					}

					out = hc.getOutputStream();
					out.write(message.getBytes("UTF-8"));
					in = hc.getInputStream();
					//
					byte[] b = GlobalData.log2(in);
					System.out.println("response" + new String(b));
					InputStream is = new ByteArrayInputStream(b);
					//
					if (hc.getResponseCode() == 200) {
						Object[] data = { new Integer(0), is };
						return data;
					}
				}
			} catch (Exception e) {
				System.out.println("Exception at NetworkThread:"
						+ e.getMessage());
				int errorID = -1;
				try {
					errorID = Integer.parseInt(e.getMessage());
				} catch (Exception ex) {
				}

				Object[] data = { new Integer(errorID), null };
				return data;
			} finally {
				try {
					if (out != null) {
						out.close();
					}
					if (in != null) {
						in.close();
					}
					if (hc != null) {
						hc.disconnect();
					}
				} catch (IOException e) {
				}

			}
		}
		return null;
	}

	@Override
	protected void onPostExecute(Object[] result) {
		if (result != null) {
			int resultCode = ((Integer) result[0]).intValue();
			InputStream is = (InputStream) result[1];
			if (resultCode == 0 && is != null) {			
				
				try {
					XmlPullParser xml = new XmlPullParser(
							new InputStreamReader(is, "UTF-8"));
					packet.parseXML(xml);
					
					progressDialog.dismiss();

				} catch (Exception e) {
					e.printStackTrace();
				}

			} else {

				progressDialog.dismiss();
				DialogScreen.show("Lỗi " + resultCode);
			}
		}

	}

	public void endLoadImage() {
		progressDialog.dismiss();
		
		Intent i = new Intent(context, MainActivity.class);
		context.startActivity(i);
	}

	@Override
	protected void onProgressUpdate(String... update) {
		if (update.length > 0)
			progressDialog.setMessage(update[0]);
	}

	public void updateMessage(String mess) {
		publishProgress(mess);
	}
}
